package com.facebook.android;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class Challenge extends Activity {
	
	private Facebook facebook;
	private Button challenge;
	private ListView list;
	private ArrayAdapter<String> adapter;
	private String[] friends;
	private static Map<String, String> reversedMap;
	private String myID;
	
	public void onCreate(Bundle savedInstanceState) {
	     super.onCreate(savedInstanceState);
	     
	     // Getting the Bundle with the information from the Intent
	     Bundle stuff = this.getIntent().getExtras();
	     // Getting the APP_ID
	     String app_id = stuff.getString("api");
	     String text = stuff.getString("friends");
	     myID = stuff.getString("myID");
	     facebook = new Facebook(app_id);
	     // Restoring the session by obtaining the session key
	     SessionStore.restore(facebook, this);  
	     
	     friends = getFriends(text);
	     if(friends[0].equals("none")){
	    	 TextView tv = new TextView(this);
	    	 tv.setText("None of your friends uses PennQuiz. Invite them!");
	    	 setContentView(tv);
	     }
	     
	     else {
		     // Set challenge layout
		     setContentView(R.layout.challenge);
		     // Get id of the challenge button
		     challenge = (Button) findViewById(R.id.challenge);
		     final Set<Long> slctdPos = new HashSet<Long>();
		     
		     // Create an adapter with the string
		     adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, friends);
		     list = (ListView) findViewById(R.id.list);
		     list.setAdapter(adapter);
		     list.setItemsCanFocus(false);
		     list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		     // Enables search by typing
		     list.setTextFilterEnabled(true);
		     
		     // Add a listener for the multiple choice list
		     list.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					
					SparseBooleanArray arr = list.getCheckedItemPositions();
					
					for(int i = 0; i < friends.length; i++){
						 if (arr.valueAt(i)){
							 Long val = list.getAdapter().getItemId(arr.keyAt(i));
							 slctdPos.add(val);
						 }
					}
				} 
		     });
		     
		     // Add a listener for the Challenge button
		     challenge.setOnClickListener(new OnClickListener(){
					@Override
					public void onClick(View v) {
						// Begin the loading dialog
						final ProgressDialog progress = ProgressDialog.show(
								Challenge.this, "", "Challenging...", true);
						
						/* CHALLENGE HERE */
						String[] chosen = new String[slctdPos.size()];
						int counter = 0;
						for(Iterator<Long> i = slctdPos.iterator(); i.hasNext(); ){
							int next = i.next().intValue();
							chosen[counter] = reversedMap.get(friends[next]);
							counter++;
						}
						
						// Execute the challenge if there are people selected
						if (chosen.length > 0){
							String chosenIDs = Arrays.toString(chosen);
							chosenIDs = chosenIDs.substring(1, chosenIDs.length()-1).replace(" ","");
							
							String domain = "http://www.pennquiz.com/users.php";
							ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
							nameValuePairs.add(new BasicNameValuePair("user",myID));
							nameValuePairs.add(new BasicNameValuePair("funct","challenge"));
							nameValuePairs.add(new BasicNameValuePair("uid", chosenIDs));
							RequestPoster rp = new RequestPoster(domain, nameValuePairs);
							rp.execute();
						}
						
						// Put the progress in a new thread, so that when it's
						// done, finish the intent.
			            new Thread(new Runnable(){
			            	public void run(){
			            		finish();
			            		progress.dismiss();
			            	}
			            	}).start();
					} 
			     });
	     }
	}
    
	/* getFriends return the user's friends from Facebook
	 * sorted by name. The function takes parameter result
	 * which is a JSONArray of all JSONObjects that
	 * represent pairs of names and IDs of the people.
	 */
    private static String[] getFriends(String result){
    	// Load the requested page converted to a string into a JSONObject.  
		JSONObject json;
		try {
			json = new JSONObject(result);
			
			// Make array of the suggestions  
			JSONArray suggestions = json.getJSONArray("data");
			Map<String, String> friends = new TreeMap<String, String>();
			reversedMap = new TreeMap<String, String>();
	
			// Build the friends map.
			for(int i = 0; i < suggestions.length(); i++){
				JSONObject single = suggestions.getJSONObject(i);
				friends.put(single.getString("id"), single.getString("name"));
				reversedMap.put(single.getString("name"), single.getString("id"));
			}

			// Format the ids string according to MySQL convention
			String ids = friends.keySet().toString();
			ids = ids.substring(1, ids.length()-1).replace(" ","");
			
			String domain = "http://www.pennquiz.com/users.php";
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("uid",ids));
			nameValuePairs.add(new BasicNameValuePair("funct","getFriends"));
			RequestPoster rp = new RequestPoster(domain, nameValuePairs);
			String[] people = rp.getFriends();
			
			if(people[0].equals("none"))
				return people;
			
			// Sort the array and return it
			for(int i = 0; i < people.length; i++){
				people[i] = friends.get(people[i]);
			}
			Arrays.sort(people);
			return people;
		}
		catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new String[]{};
    }

}
